﻿using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace SilverPortal.Util
{
	/// <summary>
	/// Xml utility methods.
	/// </summary>
	public static class XmlHelper
	{
		/// <summary>
		/// Get the value of the descendant element with the specified name and optional namespace.
		/// </summary>
		/// <param name="element"></param>
		/// <param name="name"></param>
		/// <param name="ns"></param>
		/// <returns></returns>
		public static string GetElementValue(XElement element, string name, XNamespace ns)
		{
			var descendants = element.Descendants(ns == null ? name : ns + name);
			if (descendants.Count() > 0)
				return descendants.First().Value;
			else
				return null;
		}

		public static string GetElementValue(XElement element, string name)
		{
			return GetElementValue(element, name, null);
		}

		public static int GetIntAttribute(XElement elem, string attr, int defaultValue)
		{
			XAttribute a = elem.Attribute(attr);
			if (a == null)
				return defaultValue;
			
			int result;
			if (Int32.TryParse(a.Value, out result))
				return result;

			return defaultValue;
		}
	}
}
